{% extends 'console.html' %}

{% block maincontent %}
    <!--<div class="layui-container" style="width:1300px;">-->
    <div class="layui-fluid">
        <div class="layui-card">
            <!--<div class="">数据源管理</div>-->
            <div class="layui-form layui-card-header layuiadmin-card-header-auto">
                <!-- 搜索框 -->
                <!--<div class="search-box layui-form">-->
                <!--<div class="layui-form-item" style="display: flex; justify-content: center;">-->
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">数据源</label>
                        <div class="layui-input-inline">
                            <input type="text" id="connect_name" placeholder="数据源名称" class="layui-input"
                                   lay-affix="clear">
                        </div>
                    </div>

                    <div class="layui-inline">
                        <label class="layui-form-label">IP</label>
                        <div class="layui-input-inline">
                            <!--  删除小x按钮：lay-affix="clear"  -->
                            <input type="text" id="host" placeholder="主机IP" class="layui-input"
                                   lay-affix="clear">
                        </div>
                    </div>

                    <div class="layui-inline">
                        <label class="layui-form-label">数据库</label>
                        <div class="layui-input-inline">
                            <select id="database_type" name="database_type" lay-verify="database_type" lay-search>
                                <option value="">直接选择或搜索选择</option>
                                <option value="openGauss">openGauss</option>
                                <option value="PostgreSQL">PostgreSQL</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-inline">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-inline">
                            <input type="text" id="username" placeholder="用户名" class="layui-input"
                                   lay-affix="clear">
                        </div>
                    </div>

                    <div class="layui-inline">
                        <button class="layui-btn layuiadmin-btn-list" id="btnSearch">
                            <!--<i class="layui-icon layui-icon-search"></i>搜索-->
                            <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>搜索
                        </button>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn layui-btn-primary layuiadmin-btn-list" type="reset" id="customReset">
                            <i class="layui-icon layui-icon-set-sm layuiadmin-button-btn"></i>重置
                        </button>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn layui-btn-normal layuiadmin-btn-list" id="btnAdd">
                            <i class="layui-icon layui-icon-add-circle-fine layuiadmin-button-btn"></i>添加
                        </button>
                    </div>
                </div>

            </div>

            <div class="layui-card-body">
                <!--<div style="padding-bottom: 10px;">
                    &lt;!&ndash;<button class="layui-btn layui-btn-normal layuiadmin-btn-list" id="btnAdd">
                        <i class="layui-icon layui-icon-add-circle-fine layuiadmin-button-btn"></i>添加
                    </button>&ndash;&gt;
                    &lt;!&ndash;<button class="layui-btn layuiadmin-btn-list" data-type="batchdel">删除</button>
                    <button class="layui-btn layuiadmin-btn-list" data-type="add">添加</button>&ndash;&gt;
                </div>-->
                <!-- 数据表格 -->
                <table id="ID-table-demo-search" lay-filter="ID-table-demo-search"></table>

            </div>
        </div>
    </div>

{% endblock %}

{% block script %}

    <!--<script type="text/html" id="toolbarDemo">-->
    <!--<button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add" onclick="addDatabaseSource();">
        <i class="layui-icon layui-icon-add-circle-fine"></i>添加数据源
    </button>-->
    <!--<button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add" id="btnAdd">
        <i class="layui-icon layui-icon-add-circle-fine"></i>添加数据源
    </button>-->
    <!--</script>-->

    <!-- 添加/编辑表单模板 -->
    <script type="text/html" id="formTemplate">
        <form class="layui-form" lay-filter="productForm" style="padding:20px">
            <input type="hidden" name="db_info_id">
            <div class="layui-form-item">
                <label class="layui-form-label">数据源名称</label>
                <div class="layui-input-block">
                    <input type="text" name="connect_name" id="textConnectName" lay-verify="required"
                           placeholder="请输入数据源名称"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">数据库类型</label>
                <div class="layui-input-block">
                    <select name="database_type" id="selectDatabaseType" lay-verify="required" lay-search>
                        <option value="">直接选择或搜索选择</option>
                        <option value="openGauss">openGauss</option>
                        <option value="PostgreSQL">PostgreSQL</option>
                        <!--<option value="Oracle">Oracle</option>
                        <option value="MySQL">MySQL</option>-->
                    </select>
                    <!--<input type="number" name="price" step="0.01" required lay-verify="required|number"
                           placeholder="请输入价格" class="layui-input">-->
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">主机IP</label>
                <div class="layui-input-block">
                    <input type="text" name="host" id="textHost" lay-verify="required|ip" placeholder="请输入主机IP地址"
                           autocomplete="off" class="layui-input">
                    <!--<input type="number" name="stock" required lay-verify="required|number" placeholder="请输入库存"
                           class="layui-input">-->
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">端口</label>
                <div class="layui-input-block">
                    <input type="number" name="port" id="textPort" lay-verify="required|number"
                           placeholder="请输入端口号"
                           autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">数据库名</label>
                <div class="layui-input-block">
                    <input type="text" name="dbname" id="textDbname" lay-verify="required" placeholder="请输入数据库名"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" id="textUsername" lay-verify="required"
                           placeholder="请输入用户名"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" id="textPassword" lay-verify="required"
                           placeholder="请输入密码"
                           autocomplete="off"
                           lay-affix="eye" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">描述或备注</label>
                <div class="layui-input-block">
                <textarea name="comment" id="textComment" placeholder="请输入你想描述或备注的数据库的相关信息(非必填)"
                          class="layui-textarea"></textarea>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" id="submitBtn" lay-submit lay-filter="formSubmit">提交</button>
                    <button type="button" class="layui-btn" id="closeWindowsBtn">关闭</button>
                </div>


            </div>
        </form>
    </script>

    <!-- 操作列模板 -->
    <script type="text/html" id="barOption">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs" lay-event="more">
            更多
            <i class="layui-icon layui-icon-down"></i>
        </a>
    </script>

    <!--<script src="{{ url_for('dcs.static', filename='layui/layui.js') }}"></script>-->
    <script>
        layui.use(['table', 'form', 'layer', 'dropdown'], function () {
            var $ = layui.$;
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var dropdown = layui.dropdown;

            // 初始化表格
            var tableIns = table.render({
                elem: '#ID-table-demo-search',
                url: '/dcs/api/databaseInfos',
                method: 'get',
                page: {
                    // count: data.length,            //数据总数
                    limit: 10, //每页显示条数
                    limits: [10, 20, 50, 100],
                    curr: 1, //起始页
                    groups: 5, //连续页码个数
                    prev: '上一页', //上一页文本
                    next: '下一页', //下一页文本
                    first: 1, //首页文本
                    //, last: 100                     //尾页文本
                    layout: ['prev', 'page', 'next',
                        'refresh', 'skip', 'count',
                        'limit']
                },
                // height: 600,
                // toolbar: '#toolbarDemo',
                // defaultToolbar: ['filter', 'exports'],
                cols: [
                    [ // 表头
                        // {type: 'checkbox', fixed: 'left'},
                        {
                            field: 'connect_name',
                            title: '数据源名称',
                            width: 200,
                            align: 'left',
                            fixed: 'left',
                            templet: addlink,
                            sort: true
                        },
                        {field: 'database_type', title: '数据库类型', width: 130, align: 'center'},
                        {field: 'host', title: 'IP', width: 120, align: 'left'},
                        {field: 'port', title: '端口', width: 80, align: 'left'},
                        {field: 'dbname', title: '数据库名', width: 150, edit: 'text', align: 'left'},
                        {field: 'username', title: '用户名', width: 120, edit: 'text', align: 'left'},
                        // {field: 'password', title: '密码', width:150, align: 'left'},
                        {field: 'last_update_date', title: '最后更新时间', width: 180, align: 'left', sort: true},
                        {field: 'comment', title: '描述', edit: 'text', align: 'left'},
                        {fixed: 'right', title: '操作', width: 150, toolbar: '#barOption'}
                    ]
                ]
            });

            // 监听单元格编辑
            table.on('edit(ID-table-demo-search)', function (obj) {
                const field = obj.field;
                const value = obj.value;
                const row = obj.data;

                // 发送更新请求
                $.ajax({
                    url: '/dcs/api/databaseInfoUpdate',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        id: row.db_info_id,
                        field: field,
                        value: value
                    }),
                    success: function (res) {
                        if (res.status !== 'success') {
                            layer.msg('更新失败: ' + res.message);
                            // 恢复原值
                            obj.update({[field]: row[field]});
                        } else {
                            layer.msg('更新成功!');
                            tableIns.reload();
                        }
                    },
                    error: function () {
                        layer.msg('请求失败');
                        obj.update({[field]: row[field]});
                    }
                });
            });

            // 搜索功能 - 按钮的点击事件
            $('#btnSearch').click(function () {
                loadData();
            });

            // “connect_name”输入框的回车事件
            $('#connect_name').on('keyup', function (e) {
                if (e.keyCode === 13) {
                    loadData();
                }
            });

            // “host”输入框的回车事件
            $('#host').on('keyup', function (e) {
                if (e.keyCode === 13) {
                    loadData();
                }
            });

            // “username”输入框的回车事件
            $('#username').on('keyup', function (e) {
                if (e.keyCode === 13) {
                    loadData();
                }
            });

            // 监听整个文档的回车键
            // $(document).on('keydown', function(e) {
            //     if (e.keyCode === 13) { // 回车键
            //         loadData();
            //     }
            // });

            // 自定义重置按钮事件
            $('#customReset').click(function () {
                // 1. 重置表单值
                // $('#myForm')[0].reset();

                // 重置文本框的值
                $("#connect_name").val("");
                $("#host").val("");
                $("#username").val("");

                // 重置下拉框（示例）
                $("select[name='database_type']").val("");

                // 2. 清除验证提示
                // $('.layui-form-item').removeClass('layui-form-danger');
                // $('.layui-form-mid').remove();

                // 3. 重置单选/复选框（示例）
                // $("input[name='gender']").prop("checked", false);
                // $("#checkboxDemo").prop("checked", false);

                // 4. 重置下拉框（示例）
                // $("select[name='city']").val("");

                // 5. 重新渲染表单
                form.render();

            });

            // 添加按钮
            $('#btnAdd').click(function () {
                showForm({});
            });

            // 触发单元格工具事件
            table.on('tool(ID-table-demo-search)', function (obj) {
                var data = obj.data; // 获得当前行数据
                if (obj.event === 'edit') {
                    showForm(data);
                } else if (obj.event === 'more') {
                    // 更多 - 下拉菜单
                    dropdown.render({
                        elem: this, // 触发事件的 DOM 对象
                        show: true, // 外部事件触发即显示
                        data: [{
                            title: '查看',
                            id: 'detail'
                        }, {
                            title: '测试连接',
                            id: 'checkConnect'
                        }, {
                            title: '初始化【表字段】数据',
                            id: 'initDatabaseDataToCompareSystem'
                        }, {
                            title: '初始化【索引】数据',
                            id: 'initIndexDataToCompareSystem'
                        }, {
                            title: '初始化【建表DDL脚本】数据',
                            id: 'initTableDefineDataToCompareSystem'
                        }, {
                            title: '删除',
                            id: 'del'
                        }],
                        click: function (menudata) {
                            if (menudata.id === 'detail') {
                                detailShowForm(data);
                            } else if (menudata.id === 'checkConnect') {
                                // 测试连接
                                // 使用Layui的layer.load显示加载层
                                var loadIndex = layer.load(2);
                                // 此处可执行 Ajax 等操作
                                var databaseSourceDataOfFormJson = JSON.stringify(data)
                                // console.log(databaseSourceDataOfFormJson);
                                $.ajax({
                                    url: '/dcs/api/check_connection/' + data.db_info_id,
                                    // type:'post',
                                    type: 'GET',
                                    contentType: "json",
                                    data: { // 提交数据
                                        // "databaseSourceDataOfForm": databaseSourceDataOfFormJson
                                    },
                                    success: function (data) {
                                        layer.close(loadIndex); // 关闭加载层
                                        // alert(data);
                                        // const returnDataJson = JSON.stringify(data);
                                        // alert("returnDataJson = " + returnDataJson);
                                        // alert("data.msg = " + data.msg);
                                        if (data.code === 1) {
                                            layer.alert('检查成功，连接数据库成功！', {
                                                icon: 1,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else if (data.code === -1) {
                                            layer.alert('检查失败，连接数据库失败！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else {
                                            layer.alert('未知错误！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        }
                                    },
                                    error: function (xhr, status, error) {
                                        layer.close(loadIndex); // 关闭加载层
                                        // 基础错误信息
                                        var errorMsg = "请求失败: " + status + "<br>错误码: " + xhr.status;
                                        // 尝试解析服务器返回的详细错误信息
                                        try {
                                            var response = JSON.parse(xhr.responseText);
                                            alert("response = " + response)
                                            if (response.message) errorMsg += "<br>消息: " + response.message;
                                            if (response.error) errorMsg += "<br>错误详情: " + response.error;
                                            if (response.msg) errorMsg += "<br>错误详情: " + response.msg;
                                        } catch (e) {
                                            errorMsg += "<br>响应原始数据: " + xhr.responseText;
                                        }
                                        // 控制台打印完整错误对象
                                        console.error("完整错误对象:", xhr);
                                        // 弹窗显示详细错误（使用 Layui 的 layer）
                                        layer.open({
                                            type: 1,
                                            title: '请求错误详情',
                                            area: ['500px', '300px'],
                                            content: '<div class="layui-padding">' + errorMsg + '</div>'
                                        });
                                    }
                                });
                            } else if (menudata.id === 'initDatabaseDataToCompareSystem') {
                                // 使用Layui的layer.load显示加载层
                                var loadIndex = layer.msg('后台【表字段】数据提取任务进行中，请耐心等待...', {
                                    icon: 16,
                                    shade: 0.01,
                                    time: 0
                                });
                                // 此处可执行 Ajax 等操作
                                // var databaseSourceDataOfFormJson = JSON.stringify(data)
                                // console.log(databaseSourceDataOfFormJson);
                                $.ajax({
                                    // url: '/initDatabaseDataToCompareSystem',
                                    url: '/dcs/api/initDatabaseData/' + data.db_info_id,
                                    type: 'GET',
                                    contentType: "json",
                                    data: { // 提交数据
                                        // "databaseSourceDataOfForm": databaseSourceDataOfFormJson
                                    },
                                    success: function (data) {
                                        layer.close(loadIndex); // 关闭加载层
                                        // alert(data);
                                        // const returnDataJson = JSON.stringify(data);
                                        // alert("returnDataJson = " + returnDataJson);
                                        // alert("data.msg = " + data.msg);
                                        if (data.code === 1) {
                                            layer.alert('【表字段】数据初始化成功！', {
                                                icon: 1,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else if (data.code === -1) {
                                            layer.alert('【表字段】数据初始化失败！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else {
                                            layer.alert('未知错误！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        }
                                    },
                                    error: function (xhr, status, error) {
                                        layer.close(loadIndex); // 关闭加载层
                                        // 基础错误信息
                                        var errorMsg = "请求失败: " + status + "<br>错误码: " + xhr.status;
                                        // 尝试解析服务器返回的详细错误信息
                                        try {
                                            var response = JSON.parse(xhr.responseText);
                                            // alert("response = " + response)
                                            if (response.message) errorMsg += "<br>消息: " + response.message;
                                            if (response.error) errorMsg += "<br>错误详情: " + response.error;
                                            if (response.msg) errorMsg += "<br>错误详情: " + response.msg;
                                        } catch (e) {
                                            errorMsg += "<br>响应原始数据: " + xhr.responseText;
                                        }
                                        // 控制台打印完整错误对象
                                        console.error("完整错误对象:", xhr);
                                        // 弹窗显示详细错误（使用 Layui 的 layer）
                                        layer.open({
                                            type: 1,
                                            title: '请求错误详情',
                                            area: ['500px', '300px'],
                                            content: '<div class="layui-padding">' + errorMsg + '</div>'
                                        });
                                    }
                                });
                            } else if (menudata.id === 'initIndexDataToCompareSystem') {
                                var loadIndex = layer.msg('后台【索引】数据提取任务进行中，请耐心等待...', {
                                    icon: 16,
                                    shade: 0.01,
                                    time: 0
                                });
                                $.ajax({
                                    url: '/dcs/api/initIndexInfoData/' + data.db_info_id,
                                    type: 'GET',
                                    contentType: "json",
                                    success: function (data) {
                                        layer.close(loadIndex); // 关闭加载层
                                        if (data.code === 1) {
                                            layer.alert('【索引】数据初始化成功！', {
                                                icon: 1,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else if (data.code === -1) {
                                            layer.alert('【索引】数据初始化失败！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else {
                                            layer.alert('未知错误！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        }
                                    },
                                    error: function (xhr, status, error) {
                                        layer.close(loadIndex); // 关闭加载层
                                        var errorMsg = "请求失败: " + status + "<br>错误码: " + xhr.status;
                                        try {
                                            var response = JSON.parse(xhr.responseText);
                                            // alert("response = " + response)
                                            if (response.message) errorMsg += "<br>消息: " + response.message;
                                            if (response.error) errorMsg += "<br>错误详情: " + response.error;
                                            if (response.msg) errorMsg += "<br>错误详情: " + response.msg;
                                        } catch (e) {
                                            errorMsg += "<br>响应原始数据: " + xhr.responseText;
                                        }
                                        console.error("完整错误对象:", xhr);
                                        layer.open({
                                            type: 1,
                                            title: '请求错误详情',
                                            area: ['500px', '300px'],
                                            content: '<div class="layui-padding">' + errorMsg + '</div>'
                                        });
                                    }
                                });
                            } else if (menudata.id === 'initTableDefineDataToCompareSystem') {
                                // '初始化“建表DDL脚本”数据到比对系统'
                                var loadIndex = layer.msg('后台【建表DDL脚本】提取任务进行中，请耐心等待...', {
                                    icon: 16,
                                    shade: 0.01,
                                    time: 0
                                });
                                $.ajax({
                                    url: '/dcs/api/initTableDefineData/' + data.db_info_id,
                                    type: 'GET',
                                    contentType: "json",
                                    success: function (data) {
                                        layer.close(loadIndex); // 关闭加载层
                                        if (data.code === 1) {
                                            layer.alert('【建表DDL脚本】数据初始化成功！', {
                                                icon: 1,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else if (data.code === -1) {
                                            layer.alert('【建表DDL脚本】数据初始化失败！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        } else {
                                            layer.alert('未知错误！' + data.msg, {
                                                icon: 2,
                                                shadeClose: true,
                                                title: '提示'
                                            });
                                        }
                                    },
                                    error: function (xhr, status, error) {
                                        layer.close(loadIndex); // 关闭加载层
                                        var errorMsg = "请求失败: " + status + "<br>错误码: " + xhr.status;
                                        try {
                                            var response = JSON.parse(xhr.responseText);
                                            // alert("response = " + response)
                                            if (response.message) errorMsg += "<br>消息: " + response.message;
                                            if (response.error) errorMsg += "<br>错误详情: " + response.error;
                                            if (response.msg) errorMsg += "<br>错误详情: " + response.msg;
                                        } catch (e) {
                                            errorMsg += "<br>响应原始数据: " + xhr.responseText;
                                        }
                                        console.error("完整错误对象:", xhr);
                                        layer.open({
                                            type: 1,
                                            title: '请求错误详情',
                                            area: ['500px', '300px'],
                                            content: '<div class="layui-padding">' + errorMsg + '</div>'
                                        });
                                    }
                                });

                            } else if (menudata.id === 'del') {
                                // layer.confirm('真的删除行 [id: '+ data.id +'] 么', function(index){
                                layer.confirm('确定删除吗？', function (index) {
                                    $.ajax({
                                        url: '/dcs/api/databaseInfo/' + data.db_info_id,
                                        type: 'DELETE',
                                        success: function () {
                                            layer.msg('删除成功');
                                            tableIns.reload();
                                        }
                                    });
                                    layer.close(index);
                                });
                            }
                        },
                        align: 'right', // 右对齐弹出
                        style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                    })
                } else if (obj.event === 'infoDetail') {
                    detailShowForm(data);
                }
            });

            // 查看数据详情
            function detailShowForm(data) {
                var title = '查看数据源';
                var index = layer.open({
                    type: 1,
                    title: title,
                    content: $('#formTemplate').html(),
                    area: ['550px', '650px'],
                    success: function () {
                        form.val('productForm', data);

                        // 禁用文本框
                        $("#textConnectName")
                            .attr("disabled", true)
                            // .addClass("layui-disabled")
                            .attr("placeholder", "已禁用状态");
                        $("#textHost").attr("disabled", true);
                        $("#textPort").attr("disabled", true);
                        $("#textDbname").attr("disabled", true);
                        $("#textUsername").attr("disabled", true);
                        $("#textPassword").attr("disabled", true);
                        $("#textComment").attr("disabled", true);
                        // 禁用选择框
                        $("#selectDatabaseType")
                            .attr("disabled", true)
                        // .addClass("layui-disabled")
                        ;
                        form.render('select');  // 必须重新渲染

                        // 禁用按钮
                        $("#submitBtn")
                            .attr("disabled", true)
                            .addClass("layui-btn-disabled")
                        // .text("<i class=\"layui-icon layui-icon-delete\"></i>")
                        ;
                        // $("#submitBtn").innerHTML("<i class=\"layui-icon layui-icon-delete\"></i>");
                    }
                });
                // 关闭窗口按钮
                $('#closeWindowsBtn').click(function () {
                    layer.close(index); // 关闭加载层
                });
            }

            // 显示表单弹窗
            function showForm(data) {
                var title = data.db_info_id ? '编辑数据源' : '添加数据源';
                var index = layer.open({
                    type: 1,
                    title: title,
                    content: $('#formTemplate').html(),
                    area: ['550px', '650px'],
                    // btn: ['确定', '取消'],
                    success: function () {
                        form.val('productForm', data);
                    }
                });

                // 关闭窗口按钮
                $('#closeWindowsBtn').click(function () {
                    layer.close(index); // 关闭加载层
                });

                // 表单提交
                form.on('submit(formSubmit)', function (formData) {
                    var url = formData.field.db_info_id ? '/dcs/api/databaseInfo/' + formData.field.db_info_id : '/dcs/api/databaseInfo';
                    var method = formData.field.db_info_id ? 'PUT' : 'POST';
                    // alert('url=' + url)
                    $.ajax({
                        url: url,
                        type: method,
                        contentType: 'application/json',
                        data: JSON.stringify(formData.field),
                        success: function () {
                            layer.close(index);
                            layer.msg('操作成功');
                            tableIns.reload();
                        },
                        error: function (xhr) {
                            layer.msg('操作失败: ' + xhr.responseJSON.msg);
                        }
                    });
                    return false;
                });
            }

            // 加载数据函数
            function loadData() {
                var connect_name = $('#connect_name').val();
                var host = $('#host').val();
                var database_type = $('#database_type').val();
                var username = $('#username').val();
                tableIns.reload({
                    where: {
                        connect_name: connect_name,
                        host: host,
                        database_type: database_type,
                        username: username
                    },
                    page: {curr: 1}
                });
            }

        });

        var addlink = function (d) {
            var html = '<div><a rel="nofollow" style="color:#1E9FFF" href="javascript:void(0);" lay-event="infoDetail">'
                + d.connect_name + '</a></div>';
            return html
        }


    </script>

{% endblock %}